package com.xn.app.muying.fragment;


import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.xn.app.muying.DengLuActivity;
import com.xn.app.muying.GouMaiActivity;
import com.xn.app.muying.MainActivity;
import com.xn.app.muying.MuYingApplication;
import com.xn.app.muying.R;
import com.xn.app.muying.ShouHouActivity;
import com.xn.app.muying.YanZhengActivity;
import com.xn.app.muying.ZhangHuActivity;
import com.xn.app.muying.activity.JiuZhenActivity;
import com.xn.app.muying.activity.YunQiXuanZeActivity;
import com.xn.app.muying.util.APIMethod;
import com.xn.app.muying.util.Constants;
import com.xn.app.muying.util.ToastUtil;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.lang.reflect.Type;
import java.util.HashMap;

import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * A simple {@link Fragment} subclass.
 */
public class MineFragment extends Fragment {
    Button deng_lu, zhang_hu, gou_mai, shou_hou;
    TextView yong_hu;
    boolean isLogin = false;
    private LinearLayout yunqi;
    private LinearLayout jiuzhen;
    public static TextView zhuangtai;
    public static TextView yiyuan;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        isLogin = Constants.getBooleanByName(MainActivity.mActivity, "isLogin");
        LinearLayout wode = (LinearLayout) inflater.inflate(R.layout.fragment_wo_de, container, false);
        initView(wode);
        return wode;

    }

    private void initView(LinearLayout wode) {
        deng_lu = (Button) wode.findViewById(R.id.deng_lu);
        zhang_hu = (Button) wode.findViewById(R.id.zhang_hu);
        gou_mai = (Button) wode.findViewById(R.id.gou_mai);
        shou_hou = (Button) wode.findViewById(R.id.shou_hou);
        yong_hu = (TextView) wode.findViewById(R.id.yong_hu);
        yunqi = (LinearLayout) wode.findViewById(R.id.mine_yunqixinxi_ll);
        jiuzhen = (LinearLayout) wode.findViewById(R.id.mine_jiuzhenyiyuan_ll);
        zhuangtai = (TextView) wode.findViewById(R.id.mine_zhuangtai_tv);
        yiyuan = (TextView) wode.findViewById(R.id.mine_yiyuan_tv);
        String yh = Constants.getStringByName(MainActivity.mActivity, "yonghu");
        boolean islogin = Constants.getBooleanByName(MainActivity.mActivity, "isLogin");
        if (!TextUtils.isEmpty(yh) && islogin) {
            Type type = new TypeToken<HashMap<String, String>>() {
            }.getType();
            HashMap<String, String> yy = new Gson().fromJson(yh, type);
            yong_hu.setVisibility(View.VISIBLE);
            deng_lu.setVisibility(View.GONE);
            yong_hu.setText(yy.get("userName"));
        } else {
            yong_hu.setVisibility(View.GONE);
            deng_lu.setVisibility(View.VISIBLE);
        }

//        String minemessage = Constants.getStringByName(MainActivity.mActivity, "minemessage");
//        if (!TextUtils.isEmpty(minemessage)) {
//            Type type = new TypeToken<HashMap<String, String>>() {
//            }.getType();
//            HashMap<String, String> mm = new Gson().fromJson(minemessage, type);
//            Log.i("HashMap==", mm.toString());
//            yiyuan.setText(mm.get("antenatalCareHospitalName"));
//            if (mm.get("pregnancyStatus").equals("0")) {
//                zhuangtai.setText("备孕期");
//            } else {
//                zhuangtai.setText("怀孕期");
//            }
//
//        }


        deng_lu.setOnClickListener(onclicklistener);
        zhang_hu.setOnClickListener(onclicklistener);
        gou_mai.setOnClickListener(onclicklistener);
        shou_hou.setOnClickListener(onclicklistener);
        yunqi.setOnClickListener(onclicklistener);
        jiuzhen.setOnClickListener(onclicklistener);
    }

    @Override
    public void onStart() {
        super.onStart();
        if(isLogin){
            setMine();
        }
    }

    private void setMine() {
        new Thread(new Runnable() {
//            String yonghu = null;

            @Override
            public void run() {
                try {

                    String tokens = Constants.getStringByName(getActivity(), "yonghu");
                    Type type1 = new TypeToken<HashMap<String, String>>() {
                    }.getType();

                    HashMap<String, String> token = new Gson().fromJson(tokens, type1);
                    Request request = new Request.Builder().url("http://apitest.beierbaby.com/api/account/userinfo").addHeader("Authorization", "Bearer " + token.get("access_token")).get().build();
                    okhttp3.Response response = MuYingApplication.mOkHttpClient.newCall(request).execute();

                    int code = response.code();
                    String bodys = response.body().string();
                    Log.i("code==", "code==" + code);
                    Log.i("bodys=mine=", bodys);
                    if (code == 204 || code == 200) {
                        Message msg2 = new Message();
                        msg2.what = 0;
                        msg2.obj = bodys;
                        handler1.sendMessage(msg2);

                    } else {
                        Message msg1 = new Message();
                        msg1.what = 1;
                        msg1.arg1 = code;
                        msg1.obj = bodys;
                        handler1.sendMessage(msg1);
                    }


                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }


    Handler handler1 = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 0:
                    ToastUtil.showToast(getActivity(), "修改成功");
                    onJsonMine(msg.obj.toString());
                    //将获取到的用户信息存储到SharedPreferences中
                    Constants.setStringByName(getActivity(), "minemessage", msg.obj.toString());
                    break;
                case 1:
                    ToastUtil.showToast(getActivity(), "修改失败");

                    break;
            }
        }
    };

    private void onJsonMine(String bodys) {
        try {
            JSONObject jsonObject = new JSONObject(bodys);
            String pregnancyStatus = jsonObject.optString("pregnancyStatus");
            String antenatalCareHospitalName = jsonObject.optString("antenatalCareHospitalName");
            Log.i("pregnancyStatus", pregnancyStatus.toString());
            if (pregnancyStatus.toString().equals("0")) {

                zhuangtai.setText("备孕期");
            } else {
                zhuangtai.setText("怀孕期");
            }
            yiyuan.setText(antenatalCareHospitalName);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onDestroy() {
//        getActivity().unregisterReceiver(receiver);
        super.onDestroy();
    }

    View.OnClickListener onclicklistener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.deng_lu:
                    startActivity(new Intent(MainActivity.mActivity, DengLuActivity.class));
                    break;
                case R.id.zhang_hu:
                    if (isLogin) {
                        startActivity(new Intent(MainActivity.mActivity, ZhangHuActivity.class));
                    } else {
                        ToastUtil.showToast(MainActivity.mActivity, "您还没有登录，登录后更精彩！");
                    }

                    break;
                case R.id.gou_mai:
                    startActivity(new Intent(MainActivity.mActivity, GouMaiActivity.class));
                    break;

                case R.id.shou_hou:
                    startActivity(new Intent(MainActivity.mActivity, ShouHouActivity.class));
                    break;

                case R.id.mine_yunqixinxi_ll:
                    if (isLogin) {
                        Intent intent = new Intent(MainActivity.mActivity, YunQiXuanZeActivity.class);
                        intent.putExtra("home_page", "2");
                        startActivityForResult(intent, 1);

                    } else {
                        ToastUtil.showToast(MainActivity.mActivity, "您还没有登录，登录后更精彩！");
                    }

                    break;

                case R.id.mine_jiuzhenyiyuan_ll:
                    if (isLogin) {
                        startActivityForResult(new Intent(MainActivity.mActivity, JiuZhenActivity.class), 2);
                    } else {
                        ToastUtil.showToast(MainActivity.mActivity, "您还没有登录，登录后更精彩！");
                    }
            }
        }
    };

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        //resultCode == 1是从孕期信息页面返回的数据
        if (resultCode == 1) {
            String yiyuanming = data.getExtras().getString("yiyuanming");
            int yiyuanid = data.getExtras().getInt("yiyuanid");
            Log.i("yiyuanid",yiyuanming+yiyuanid);
                jiuzhenyiyuan(yiyuanid);

//resultCode == 2是从就诊医院页面返回的数据
        } else if (resultCode == 2) {
            String result = data.getExtras().getString("yiyuan");
            yiyuan.setText(result);
            String s = yiyuan.getText().toString();
            int id = data.getExtras().getInt("id");
            Log.i("resultid", id+result);
            if (!TextUtils.isEmpty(s)) {
                jiuzhenyiyuan(id);
            }
        }
    }


    private void jiuzhenyiyuan(final int id) {
        new Thread(new Runnable() {
//            String yonghu = null;

            @Override
            public void run() {
                try {
                    HashMap<String, Integer> param = new HashMap<>();
                    param.put("antenatalCareHospitalId", id);
                    String p = new Gson().toJson(param);
                    Log.i("allen", p);

                    String tokens = Constants.getStringByName(getActivity(), "yonghu");
                    Type type1 = new TypeToken<HashMap<String, String>>() {
                    }.getType();
                    HashMap<String, String> token = new Gson().fromJson(tokens, type1);
                    Log.i("asdf", "access_token==" + "Bearer " + token.get("access_token"));
                    RequestBody formBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), p);
                    Request request = new Request.Builder().url("http://apitest.beierbaby.com/api/account/userinfo/antenatalcare-hospital").addHeader("Authorization", "Bearer " + token.get("access_token")).put(formBody).build();
                    okhttp3.Response response = MuYingApplication.mOkHttpClient.newCall(request).execute();

                    int code = response.code();
                    String bodys = response.body().string();

                    Log.i("code==", "code==" + code);
                    Log.i("bodys==", bodys);
                    if (code == 204 || code == 200) {
                        Message msg2 = new Message();
                        msg2.what = 0;
                        msg2.obj = bodys;
                        handler.sendMessage(msg2);
                    } else {
                        Message msg1 = new Message();
                        msg1.what = 1;
                        msg1.arg1 = code;
                        msg1.obj = bodys;
                        handler.sendMessage(msg1);
                    }


                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }


    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 0:
                    ToastUtil.showToast(getActivity(), "修改成功");
                    break;
                case 1:
                    ToastUtil.showToast(getActivity(), "修改失败");

                    break;
            }
        }
    };
}


